package com.db.history.files;

import com.db.services.Settings;

import java.io.*;

/**
 * Created by Student on 25.11.2014.
 * File instead of DB. Write and read messages from this file
 */
public class FileOperations {

    private BufferedMessageWriter bmw;

    public FileOperations() {
        try {
            clearFile();
            bmw = new BufferedMessageWriter();
        } catch (IOException e) {
            System.out.println(new StringBuffer("Ошибка при доступе к файлу ").append(Settings.FILE_NAME).append("\n").append(e.getStackTrace()).toString());

        }

    }

    private static boolean clearFile() {
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(Settings.FILE_NAME);
        } catch (FileNotFoundException e) {
            System.out.println(new StringBuffer("Не найден файл ").append(Settings.FILE_NAME).append("\n").append(e.getStackTrace()).toString());
            return false;
        }
        writer.print("");
        writer.close();
        return true;
    }


    public boolean SaveToFile(String message) {
        try {
            bmw.addMessage(message);
        } catch (IOException e) {
            System.out.println(new StringBuffer("Ошибка при сохранении в файл ").append(Settings.FILE_NAME).append("\n").append(e.getStackTrace()).toString());
            return false;
        }
        return true;
    }


    public StringBuffer ReadFile() {
        try {
            bmw.flush();
        }catch (IOException e){
            System.out.println(new StringBuffer("Ошибка при обращении в файл ").append(Settings.FILE_NAME).append("\n").append(e.getStackTrace()).toString());
        }
        StringBuffer sb = new StringBuffer();
        String line = null;
        try (BufferedReader in = new BufferedReader(new FileReader(new File(Settings.FILE_NAME)))) {
            while ((line = in.readLine()) != null)
                sb.append(line + "\n");
        } catch (FileNotFoundException e) {
            System.out.println(new StringBuffer("Не найден файл ").append(Settings.FILE_NAME).append("\n").append(e.getStackTrace()).toString());
            return null;
        } catch (IOException e) {
            System.out.println(new StringBuffer("Ошибка при чтении из файла ").append(Settings.FILE_NAME).append("\n").append(e.getStackTrace()).toString());
            return null;
        }
        return sb;
    }
}
